package com.fishingwithme.android.ui.viewmodels

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.fishingwithme.android.data.model.CreditLevelRule
import com.fishingwithme.android.data.repository.FishingRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class CreditLevelsViewModel @Inject constructor(
    private val repository: FishingRepository
) : ViewModel() {

    private val _uiState = MutableStateFlow<CreditLevelsUiState>(CreditLevelsUiState.Loading)
    val uiState: StateFlow<CreditLevelsUiState> = _uiState

    init {
        loadCreditLevels()
    }

    fun loadCreditLevels() {
        viewModelScope.launch {
            _uiState.value = CreditLevelsUiState.Loading
            repository.getCreditLevels()
                .catch { e ->
                    _uiState.value = CreditLevelsUiState.Error(e.message ?: "Failed to load credit levels")
                }
                .collect { result ->
                    result.fold(
                        onSuccess = { levels ->
                            _uiState.value = CreditLevelsUiState.Success(levels)
                        },
                        onFailure = { error ->
                            _uiState.value = CreditLevelsUiState.Error(error.message ?: "Failed to load credit levels")
                        }
                    )
                }
        }
    }

    fun retry() {
        loadCreditLevels()
    }
}

sealed class CreditLevelsUiState {
    object Loading : CreditLevelsUiState()
    data class Success(val levels: List<CreditLevelRule>) : CreditLevelsUiState()
    data class Error(val message: String) : CreditLevelsUiState()
}